<?php defined('slim') or exit('访问不合法'); ?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css"
          integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <title>公共聊天</title>
    <script src="/data/js/jquery.js"></script>
    <script src="https://wow.techbrood.com/libs/jquery/jquery-1.11.1.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/js-cookie@2/src/js.cookie.min.js"></script>
    <script src="/data/layer/layer.js"></script>
    <link rel="stylesheet" href="/data/css/ini.css">
    <link rel="stylesheet" href="/data/css/animate.css">
</head>
<?php require_once BASE_PATH_VIEW . '/live2d.php' ?>
<style>
    * {
        box-sizing: border-box;
        font-family: 'Source Sans Pro', sans-serif;
        font-weight: 300;
    }

    .floated-parent {
        overflow: auto;
    }

    section {
        width: 100%;
        height: 100vh;
        background-color: rgba(0, 0, 0, .5);
    }

    #message-box {
        position: absolute;
        left: 0;
        right: 0;
        bottom: 0;
        top: 0;
        margin: auto;
        -webkit-box-shadow: 0px 0px 59px 5px rgba(0, 0, 0, 0.58);
        -moz-box-shadow: 0px 0px 59px 5px rgba(0, 0, 0, 0.18);
        box-shadow: 0px 0px 59px 5px rgba(0, 0, 0, 0.18);
        overflow: hidden;
        width: 70%;
        height: 70%;
        max-width: 1000px;
        background-color: white;
    }

    nav {
        display: inline-block;
        float: left;
        width: 15%;
        height: 100%;
        padding: 20px;
        text-align: center;
        background-color: #777;
        overflow: scroll;
    }

    @media only screen and (max-width: 1000px) {
        nav {
            width: 25%;
        }
    }

    @media only screen and (max-width: 600px) {
        nav {
            width: 30%;
        }
    }

    ::-webkit-scrollbar {
        width: 0px;
        /* remove scrollbar space */

        background: transparent;
        /* optional: just make scrollbar invisible */
    }

    .message-area {
        display: inline-block;
        float: left;
        width: 85%;
        height: 100%;
    }

    @media only screen and (max-width: 1000px) {
        .message-area {
            width: 75%;
        }
    }

    @media only screen and (max-width: 600px) {
        .message-area {
            width: 70%;
        }
    }

    .message-area #current-contact {
        width: 100%;
        height: 15%;
        border-bottom: 1px solid grey;
    }

    .message-area #current-contact h1 {
        text-align: center;
        text-transform: uppercase;
        font-weight: 600;
        letter-spacing: .1em;
        line-height: 75px;
        font-size: large;
        margin: auto;
    }

    .message-area #conversation-area {
        height: 75%;
        width: 100%;
        padding: 10px 40px;
        overflow: scroll;
    }

    @media only screen and (max-width: 600px) {
        .message-area #conversation-area {
            padding: 10px;
        }
    }

    .message-area #conversation-area .conversation {
        display: none;
    }

    .message-area #conversation-area .current {
        display: initial;
    }

    .message-area #conversation-area .text-bubble {
        width: 50%;
        padding: 20px 10px;
        margin: 7px;
        border-radius: 5px;
    }

    @media only screen and (max-width: 600px) {
        .message-area #conversation-area .text-bubble {
            width: 80%;
        }
    }

    .message-area #conversation-area .recieved {
        background-color: #1abc9c;
        color: white;
        clear: both;
    }

    .message-area #conversation-area .sent {
        background-color: #EEEEEE;
        color: black;
        float: right;
        clear: both;
    }

    .message-area #text-input {
        height: 10%;
        width: 100%;
    }

    .message-area #text-input input {
        width: 100%;
        height: 100%;
        resize: none;
        border: none;
        border-top: 1px solid black;
        padding: 20px 20px 20px 50px;
    }

    .message-area #text-input input:focus {
        outline: 0;
    }

    .chip {
        cursor: pointer;
        display: block;
        width: 60px;
        height: 60px;
        font-size: 13px;
        font-weight: 900;
        line-height: 50px;
        margin: 30px auto;
        border-radius: 50%;
        border: 3px solid #cccccca8;
        color: #cccccca8;
        -webkit-transition: -webkit-transform 0.2s cubic-bezier(0.87, -0.41, 0.19, 1.44);
        transition: transform 0.2s cubic-bezier(0.87, -0.41, 0.19, 1.44);
    }

    .online {
        border: 3px solid #1abc9c;
        color: white;
    }

    .chip:hover {
        transform: scale(1.05, 1.05);
    }

    .sendtime {
        float: right;
        clear: both;
    }

</style>

<section>
    <div id="message-box">
        <nav>
            <div class="contact chip online" id="0">群聊</div>
            <!--            <img src="https://randomuser.me/api/portraits/men/49.jpg" class="contact chip" id="chip-1">-->
            <!--            <img src="https://randomuser.me/api/portraits/women/24.jpg" class="contact chip" id="chip-2">-->
            <!--            <img src="https://randomuser.me/api/portraits/men/66.jpg" class="contact chip" id="chip-3">-->
            <!--            <img src="https://randomuser.me/api/portraits/women/15.jpg" class="contact chip" id="chip-4">-->
        </nav>
        <div class="message-area">
            <div id="current-contact">
                <h1>群聊</h1>
            </div>
            <div id="conversation-area">
                <div class="conversation current" id="convo-0">
                </div>
            </div>
            <form action="#" id="text-input">
                <input type="text" name="txt" onkeypress="handle(event)" id="text-content" autocomplete="off"
                       placeholder="Type message..."/>
            </form>
        </div>
    </div>
</section>

<script color="255,192,203" opacity='100' zIndex="999" count="20" src="/data/js/canvas-nest.js"></script>
<!--<script src="--><?php //echo BASE_URL_JS;?><!--/index.js"></script>-->
<script>
    var pn = 1;
    var page = 10;
    var hasmore = true;
    var uid = 0;
    var url = "ws://45.40.207.184:9502";
    var socket = '';
    $(function () {
        //获取首页数据
        getchat();
        Connect();

        //正在输入
        $('#text-content').on('focus', function () {
            if (uid > 0) {
                var state = {
                    type: 'isinput',
                    state: 1,
                    send: Cookies.get('member_id'),
                    rece: uid
                };
                socket.send(JSON.stringify(state));
            }

        });
        $('#text-content').on('blur', function () {
            if (uid > 0) {
                var state = {
                    type: 'isinput',
                    state: 0,
                    send: Cookies.get('member_id'),
                    rece: uid
                };
                socket.send(JSON.stringify(state));
            }

        });

        $("#text-input").submit(function (e) {
            e.preventDefault();
        });
        //好友列表
        $.ajax({
            url: '/userList',
            data: {},
            type: 'get',
            dataType: 'json',
            success: function (res) {
                if (res.state == 200) {
                    var userlist = '';
                    $.each(res.data, function (k, v) {
                        userlist += '<div class="contact chip user" id="' + v.user_id + '">' + v.user_name + '</div>';
                    });
                    $('nav').append(userlist);
                }
                //点击头像事件
                $(".chip").click(function () {

                    //给全局变量声明当前聊天对象
                    uid = $(this).attr('id');
                    //判断是否存在页面元素
                    if ($('#convo-' + uid).size() <= 0) {
                        //不存在生成页面,需要再次发起请求
                        pn = 1;
                        hasmore = true;
                        $('<div class="conversation" id="convo-' + uid + '"></div>').appendTo($('#conversation-area'));
                        getchat();
                    }
                    //展示页面
                    $(".conversation").removeClass('current');
                    $("#convo-" + uid).addClass("current");

                    //标题
                    var name = $(this).html();
                    $("#current-contact h1").html(name);

                    scrollbottom();

                });
            },
            error: function (error) {
                console.log(error)
            }
        });

    });

    //链接websocket
    function Connect() {
        //兼容 FireFox
        if ("WebSocket" in window) {
            socket = new WebSocket(url);
        } else if ("MozWebSocket" in window) {
            socket = new MozWebSocket(url);
        }
        socket.onopen = function (event) {
            console.log('连接成功!');
        };
        //当客户端收到服务端发来的消息时，会触发onmessage事件，参数event.data中包含server传输过来的数据
        socket.onmessage = function (event) {
            var content = event.data;//获取消息
            content = JSON.parse(content);
            console.log("收到消息： ", content);
            //正在输入信息
            if (content.type == 'isinput') {
                if (Cookies.get('member_id') == content.rece && uid == content.send) {
                    if (content.state == 1) {
                        $('h1').html($('#' + content.send).html() + '(正在输入...)');
                    } else {
                        $('h1').html($('#' + content.send).html());
                    }

                }
            }
            // console.log(content);

            //消息信息
            if (content.type == 'message') {
                var message = content.data;
                if (Object.keys(message).length > 0 && message.chat_content != '') {
                    if (Cookies.get('member_id') == message.chat_user_id) {
                        var str = '<p class="text-bubble sent">' + message.chat_content + '</p>' +
                            '<p class="sendtime">' + message.add_time + '</p>';
                        $(document).find("#convo-" + uid).append(str);
                    } else {
                        var str = '<p class="text-bubble recieved">' + message.chat_content + '</p>' +
                            '<p class="recievetime">' + message.add_time + ' by ' + message.chat_user_name + '</p>';
                        if (message.rece_user_id == 0) {
                            $(document).find("#convo-" + message.rece_user_id).append(str);
                        } else {
                            $(document).find("#convo-" + message.chat_user_id).append(str);
                        }
                        // $(document).find("#convo-"+message.rece_user_id).append(str);
                    }
                    scrollbottom();
                }
            }

            //提醒类型消息
            if (content.type == 'onlineList') {
                console.log('当前在线人数:', content.data);
                $('.user').removeClass('online');
                if (content.data) {
                    $.each(content.data, function (k, v) {
                        $("#" + v).addClass('online');
                        $('.chip').eq(0).after($("#" + v));
                    });
                }

            }

        };
        socket.onclose = function (evt) {
            console.log("WebSocketClosed!");
            Connect();
        };
        socket.onerror = function (evt) {
            console.log("WebSocketError!");
        };
    }

    //发送消息事件
    function handle(e) {
        if (e.keyCode === 13) {
            var content = $('#text-content').val();
            if (content.length > 0) {
                var data = {content: content, uid: uid};
                $.ajax({
                    url: '/chat',
                    data: data,
                    type: 'post',
                    dataType: 'json',
                    success: function (res) {
                        if (res.state == 200) {
                            $('#text-content').val('');
                            $('#text-content').blur();
                            scrollbottom();
                        } else {
                            alert('发送失败');
                        }

                    }
                });

            }


        }

        return false;
    }

    //获取聊天记录,群聊和单聊
    function getchat() {
        if (!hasmore) {
            return;
        }
        $.ajax({
            url: '/chatlist',
            data: {pn: pn, page: page, uid: uid},
            async: false,
            type: 'get',
            dataType: 'json',
            success: function (res) {
                if (res.state == 200 && res.data.length > 0) {
                    var str = '';
                    $.each(res.data, function (k, v) {
                        if (v.chat_user_id == Cookies.get('member_id')) {
                            str += '<p class="text-bubble sent">' + v.chat_content + '</p>' +
                                '<p class="sendtime">' + v.add_time + '</p>';
                        } else {
                            str += '<p class="text-bubble recieved">' + v.chat_content + '</p>' +
                                '<p class="recievetime">' + v.add_time + ' by ' + v.chat_user_name + '</p>';
                        }
                    });
                    $(str).appendTo("#convo-" + uid);
                    scrollbottom();
                    pn++;
                } else {
                    hasmore = false;
                }
            }
        });
    }

    //聊天框拉到底部
    function scrollbottom() {
        var objDiv = document.getElementById("conversation-area");
        objDiv.scrollTop = objDiv.scrollHeight;
    }
</script>
</html>
